package l1j.server.echo;

import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;




	// 帳號處理的程序
public	class PacketHc implements Runnable {

	private static final Logger _log = Logger.getLogger(PacketHc.class.getName());

		private final Queue<byte[]> _queue;

		private final PacketHandler _handler;

		private final ClientThread _client ;

		public PacketHc(ClientThread client) {
			this._client = client;
			this._queue = new ConcurrentLinkedQueue<byte[]>();
			this._handler = new PacketHandler(this._client);

		}

		public PacketHc(ClientThread client,final int capacity) {
			this._client = client;
			this._queue = new LinkedBlockingQueue<byte[]>(capacity);
			this._handler = new PacketHandler(this._client);
		}

		public void requestWork(final byte data[]) {
			this._queue.offer(data);
		}

		@Override
		public void run() {
			try {
				while (this._client.get_socket() != null) {
					for (final Iterator<byte[]> iter = this._queue.iterator(); iter.hasNext();) {
						final byte[] decrypt = iter.next();
						iter.remove();
						this._handler.handlePacket(decrypt);
						Thread.sleep(1);
					}
					// 隊列為空 休眠
					Thread.sleep(10);
				}

				// 垃圾回收
				//finalize();

			} catch (final Exception e) {
				_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

			/*} catch (Throwable e) {
				_log.error(e.getLocalizedMessage(), e);//*/

			} finally {
				// 移除此 collection 中的所有元素
				this._queue.clear();
			}
		}
	}
